package zy.service.sys.reward.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import zy.dao.sys.reward.RewardDAO;
import zy.entity.PageData;
import zy.entity.PageInfo;
import zy.entity.sys.reward.T_Sys_Reward;
import zy.entity.sys.user.T_Sys_User;
import zy.service.sys.reward.RewardService;
import zy.util.CommonUtil;

@Service
public class RewardServiceImpl implements RewardService{
	@Resource
	private RewardDAO rewardDAO;
	
	@Override
	public PageData<T_Sys_Reward> page(Map<String, Object> params) {
		Assert.notNull(params.get(CommonUtil.COMPANYID),"连接超时，请重新登录!");
		Object pageSize = params.get(CommonUtil.PAGESIZE);
		Object pageIndex = params.get(CommonUtil.PAGEINDEX);
		Integer _pageSize = (Integer)pageSize;
		Integer _pageIndex = (Integer)pageIndex;
		
		Integer totalCount = rewardDAO.count(params);
		PageInfo pageInfo = new PageInfo(totalCount, _pageSize, _pageIndex);
		params.put(CommonUtil.START, (_pageIndex-1)*_pageSize);
		params.put(CommonUtil.END, _pageSize);
		
		List<T_Sys_Reward> list = rewardDAO.list(params);
		PageData<T_Sys_Reward> pageData = new PageData<T_Sys_Reward>();
		pageData.setPageInfo(pageInfo);
		pageData.setList(list);
		return pageData;
	}
	
	@Override
	public T_Sys_Reward load(Integer rw_id) {
		return rewardDAO.load(rw_id);
	}
	
	@Override
	@Transactional
	public void save(T_Sys_Reward reward, T_Sys_User user) {
		Assert.hasText(reward.getRw_name(),"名称不能为空");
		Assert.notNull(reward.getRw_score(),"分数不能为空");
		reward.setCompanyid(user.getCompanyid());
		if(CommonUtil.ONE.equals(user.getShoptype()) || CommonUtil.TWO.equals(user.getShoptype()) || CommonUtil.FOUR.equals(user.getShoptype())){//总公司、分公司、加盟
			reward.setRw_shop_code(user.getUs_shop_code());
		}else{//自营、合伙
			reward.setRw_shop_code(user.getShop_upcode());
		}
		T_Sys_Reward existReward = rewardDAO.check(reward);
		if (existReward != null) {
			throw new RuntimeException("奖励已存在!");
		}
		rewardDAO.save(reward);
	}
	
	@Override
	@Transactional
	public void update(T_Sys_Reward reward, T_Sys_User user) {
		Assert.hasText(reward.getRw_name(),"名称不能为空");
		Assert.notNull(reward.getRw_score(),"分数不能为空");
		reward.setCompanyid(user.getCompanyid());
		if(CommonUtil.ONE.equals(user.getShoptype()) || CommonUtil.TWO.equals(user.getShoptype()) || CommonUtil.FOUR.equals(user.getShoptype())){//总公司、分公司、加盟
			reward.setRw_shop_code(user.getUs_shop_code());
		}else{//自营、合伙
			reward.setRw_shop_code(user.getShop_upcode());
		}
		T_Sys_Reward existReward = rewardDAO.check(reward);
		if (existReward != null) {
			throw new RuntimeException("奖励已存在!");
		}
		rewardDAO.update(reward);
	}
	
	@Override
	@Transactional
	public void del(Integer rw_id) {
		//TODO 验证是否存在业务关联
		rewardDAO.del(rw_id);
	}
	
}
